<template>
  <div class="role-management">
    <div class="role-container">
      <!-- 头部操作区 -->
      <div class="header-actions">
        <el-button type="primary" @click="handleAddRole">
          创建角色
        </el-button>
      </div>

      <!-- 角色表格 -->
      <div class="common-table-container">
        <table class="common-table">
          <thead>
            <tr>
              <th style="width: 80px;">序号</th>
              <th>角色名称</th>
              <th style="width: 100px;">权重</th>
              <th style="width: 100px;">排序</th>
              <th style="width: 200px;">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="role in roleData" :key="role.id">
              <td>{{ role.id }}</td>
              <td>{{ role.role_name }}</td>
              <td>{{ role.weight }}</td>
              <td>{{ role.orderid }}</td>
              <td v-if="role.id != 1">
                <button @click="handleAssignPermission(role)" class="action-btn" title="分配权限">
                  <el-icon>
                    <User />
                  </el-icon>
                </button>
                <button @click="handleEditRole(role)" class="action-btn" title="编辑">
                  <el-icon>
                    <Edit />
                  </el-icon>
                </button>
                <button @click="handleDeleteRole(role)" class="action-btn delete-btn" title="删除">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog v-model="roleDialogVisible" :title="roleDialogTitle" width="500px" @close="resetRoleForm">
      <el-form ref="roleFormRef" :model="roleForm" :rules="roleRules" label-width="100px">
        <el-form-item label="角色名称" prop="role_name">
          <el-input v-model="roleForm.role_name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="权重" prop="weight">
          <el-input-number v-model="roleForm.weight" :min="0" :max="20" />
        </el-form-item>
        <el-form-item label="排序" prop="orderid">
          <el-input-number v-model="roleForm.orderid" :min="0" />
        </el-form-item>
        <el-form-item label="是否管理员" prop="is_admin">
          <el-select v-model="roleForm.is_admin" placeholder="请选择">
            <el-option label="是" value="1" />
            <el-option label="否" value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRoleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog v-model="permissionDialogVisible" :title="`分配权限：【${currentRole.role_name}】`" width="900px"
      @close="handleClosePermission" class="permission-dialog">



      <div class="permission-content">
        <!-- 空状态 -->
        <div v-if="permTreeData.length === 0 && !loading" class="permission-empty">
          <el-icon>
            <Folder />
          </el-icon>
          <div class="empty-text">暂无权限数据</div>
          <div class="empty-desc">请联系管理员配置权限</div>
        </div>

        <!-- 一级菜单 -->
        <div v-for="(item, index) in permTreeData" :key="index" class="perm-module">
          <div class="module-header">
            <div class="module-info">
              <el-icon class="module-icon">
                <Folder />
              </el-icon>
              <span class="module-name">{{ item.menu_name }}</span>
              <span class="module-stats">({{ getModuleStats(item) }})</span>
            </div>
            <div class="module-actions">
              <el-checkbox v-model="item.ck" :indeterminate="getModuleIndeterminate(item)"
                @change="handleModuleSelectAll($event, item)" class="module-checkbox">
                全选
              </el-checkbox>
            </div>
          </div>

          <div class="module-content" v-show="item.children && item.children.length">
            <!-- 二级菜单 -->
            <div class="perm-group" v-for="item2 in item.children" :key="item2.id">
              <div v-if="item2.children && item2.children.length" class="group-with-children">
                <div class="group-header">
                  <span class="group-name">{{ item2.menu_name }}</span>
                  <div class="group-actions">
                    <el-checkbox v-model="item2.ck" :indeterminate="getGroupIndeterminate(item2)"
                      @change="handleGroupSelectAll($event, item2)" size="small">
                      全选
                    </el-checkbox>
                  </div>
                </div>
                <div class="group-permissions">
                  <el-checkbox v-for="item3 in item2.children" :key="item3.id" v-model="item3.ck"
                    @change="handlePermissionChange" class="permission-item">
                    {{ item3.menu_name }}
                  </el-checkbox>
                </div>
              </div>
              <div v-else class="group-single">
                <el-checkbox v-model="item2.ck" @change="handlePermissionChange" class="permission-item single">
                  {{ item2.menu_name }}
                </el-checkbox>
              </div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <div class="footer-info">
            <el-icon>
              <InfoFilled />
            </el-icon>
            <span>共 {{ totalPermissionCount }} 项权限，已选择 {{ selectedPermissionCount }} 项</span>
          </div>
          <div class="footer-actions">
            <el-button @click="permissionDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handlePermissionSubmit" :loading="submitting">
              确定分配
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Folder, InfoFilled } from '@element-plus/icons-vue'
import { roleApi } from '@/api/role'
import { Edit, Delete, User } from '@element-plus/icons-vue'
// 响应式数据
const roleData = ref([])
const roleDialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const roleFormRef = ref()
const currentRole = ref({})
const loading = ref(false)
const tableLoading = ref(false)

// 角色表单
const roleForm = reactive({
  id: '',
  role_name: '',
  is_admin: '0',
  weight: 0,
  orderid: 0
})

// 权限相关数据
const permTreeData = ref([])
const submitting = ref(false)

// 权限统计计算属性
const selectedPermissionCount = computed(() => {
  let count = 0
  permTreeData.value.forEach(item => {
    if (item.children) {
      item.children.forEach(item2 => {
        if (item2.children && item2.children.length) {
          item2.children.forEach(item3 => {
            if (item3.ck) count++
          })
        } else {
          if (item2.ck) count++
        }
      })
    }
  })
  return count
})

const totalPermissionCount = computed(() => {
  let count = 0
  permTreeData.value.forEach(item => {
    if (item.children) {
      item.children.forEach(item2 => {
        if (item2.children && item2.children.length) {
          count += item2.children.length
        } else {
          count++
        }
      })
    }
  })
  return count
})

// 表单验证规则
const roleRules = {
  role_name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  weight: [
    { required: true, message: '请输入权重', trigger: 'blur' }
  ]
}

// 计算属性
const roleDialogTitle = computed(() => {
  return roleForm.id ? '编辑角色' : '新增角色'
})

// 初始化数据
const initData = async () => {
  try {
    await loadRoleList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('加载角色数据失败')
  }
}

// 加载角色列表
const loadRoleList = async () => {
  try {
    tableLoading.value = true
    const response = await roleApi.getRoleList()
    if (response.status) {
      roleData.value = response.data.list
    } else {
      throw new Error(response.message || '获取角色数据失败')
    }
  } catch (error) {
    console.error('加载角色列表失败:', error)
    throw error
  } finally {
    tableLoading.value = false
  }
}


// 方法
const handleAddRole = () => {
  resetRoleForm()
  roleDialogVisible.value = true
}

const handleEditRole = (role) => {
  Object.assign(roleForm, role)
  roleDialogVisible.value = true
}

const handleDeleteRole = async (role) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色"${role.role_name}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 调用删除接口
    await roleApi.deleteRole(role.id)
    ElMessage.success('删除成功')

    // 重新加载角色列表
    await loadRoleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除角色失败:', error)
      ElMessage.error('删除失败')
    } else {
      ElMessage.info('已取消删除')
    }
  }
}





const handleRoleSubmit = async () => {
  try {
    await roleFormRef.value.validate()

    const isEdit = !!roleForm.id
    const apiCall = isEdit
      ? roleApi.updateRole(roleForm)
      : roleApi.createRole(roleForm)

    await apiCall
    ElMessage.success(isEdit ? '编辑成功' : '新增成功')
    roleDialogVisible.value = false

    // 重新加载角色列表
    await loadRoleList()
  } catch (error) {
    if (error.message) {
      console.error('角色操作失败:', error)
      ElMessage.error(error.message || '操作失败')
    } else {
      console.error('表单验证失败:', error)
    }
  }
}



const resetRoleForm = () => {
  Object.assign(roleForm, {
    id: '',
    role_name: '',
    is_admin: '0',
    weight: 0,
    orderid: 0
  })
  roleFormRef.value?.clearValidate()
}

// 分配权限相关方法
const handleAssignPermission = async (role) => {
  currentRole.value = role
  permissionDialogVisible.value = true
  await loadRolePermissions(role.id)
}

// 加载角色权限
const loadRolePermissions = async (roleId) => {
  try {
    loading.value = true

    // 并行获取权限树和角色权限
    const rolePermissionsResponse = await Promise.all([
      roleApi.getRolePermissions(roleId)
    ])
    if (rolePermissionsResponse[0].status) {
      const menuList = rolePermissionsResponse[0].data.menu_list || []
      const funcList = rolePermissionsResponse[0].data.func_list || []
      setPermissionData(funcList, menuList)
    }

  } catch (error) {
    console.error('加载权限失败:', error)
    ElMessage.error('加载权限失败')
  } finally {
    loading.value = false
  }
}


// 设置权限数据
const setPermissionData = (funcList, menuList) => {
  const data = JSON.parse(JSON.stringify(menuList))

  data.forEach(item => {
    item.ck = false
    item.children.forEach(item2 => {
      item2.ck = false
      if (item2.children && item2.children.length) {
        // 检查二级菜单是否被选中
        if (funcList && funcList.includes(item2.id)) {
          item2.ck = true
        }

        item2.children.forEach(item3 => {
          item3.ck = false
          // 检查三级菜单是否被选中
          if (funcList && funcList.includes(item3.id)) {
            item3.ck = true
          }
        })
      } else {
        // 没有子菜单的二级菜单
        if (funcList && funcList.includes(item2.id)) {
          item2.ck = true
        }
      }
    })
  })

  permTreeData.value = data
}



// 模块级操作
const handleModuleSelectAll = (checked, item) => {
  item.ck = checked
  item.children.forEach(item2 => {
    item2.ck = checked
    if (item2.children && item2.children.length) {
      item2.children.forEach(item3 => {
        item3.ck = checked
      })
    }
  })
}



// 分组级操作
const handleGroupSelectAll = (checked, item2) => {
  item2.ck = checked
  if (item2.children && item2.children.length) {
    item2.children.forEach(item3 => {
      item3.ck = checked
    })
  }
  // 更新父级状态
  updateParentStatus()
}



// 权限项变化处理
const handlePermissionChange = () => {
  updateParentStatus()
}

// 状态更新方法
const updateModuleStatus = (item) => {
  if (!item.children) return

  let checkedCount = 0
  let totalCount = 0

  item.children.forEach(item2 => {
    if (item2.children && item2.children.length) {
      item2.children.forEach(item3 => {
        totalCount++
        if (item3.ck) checkedCount++
      })
    } else {
      totalCount++
      if (item2.ck) checkedCount++
    }
  })

  if (checkedCount === 0) {
    item.ck = false
  } else if (checkedCount === totalCount) {
    item.ck = true
  } else {
    item.ck = false // 半选状态通过 indeterminate 处理
  }
}

const updateGroupStatus = (item2) => {
  if (!item2.children || !item2.children.length) return

  const checkedCount = item2.children.filter(item3 => item3.ck).length
  const totalCount = item2.children.length

  if (checkedCount === 0) {
    item2.ck = false
  } else if (checkedCount === totalCount) {
    item2.ck = true
  } else {
    item2.ck = false // 半选状态通过 indeterminate 处理
  }
}

const updateParentStatus = () => {
  permTreeData.value.forEach(item => {
    // 更新分组状态
    if (item.children) {
      item.children.forEach(item2 => {
        updateGroupStatus(item2)
      })
    }
    // 更新模块状态
    updateModuleStatus(item)
  })
}

// 获取模块统计信息
const getModuleStats = (item) => {
  if (!item.children) return '0/0'

  let checkedCount = 0
  let totalCount = 0

  item.children.forEach(item2 => {
    if (item2.children && item2.children.length) {
      item2.children.forEach(item3 => {
        totalCount++
        if (item3.ck) checkedCount++
      })
    } else {
      totalCount++
      if (item2.ck) checkedCount++
    }
  })

  return `${checkedCount}/${totalCount}`
}

// 获取模块半选状态
const getModuleIndeterminate = (item) => {
  if (!item.children) return false

  let checkedCount = 0
  let totalCount = 0

  item.children.forEach(item2 => {
    if (item2.children && item2.children.length) {
      item2.children.forEach(item3 => {
        totalCount++
        if (item3.ck) checkedCount++
      })
    } else {
      totalCount++
      if (item2.ck) checkedCount++
    }
  })

  return checkedCount > 0 && checkedCount < totalCount
}

// 获取分组半选状态
const getGroupIndeterminate = (item2) => {
  if (!item2.children || !item2.children.length) return false

  const checkedCount = item2.children.filter(item3 => item3.ck).length
  const totalCount = item2.children.length

  return checkedCount > 0 && checkedCount < totalCount
}



// 关闭权限对话框
const handleClosePermission = () => {
  permissionDialogVisible.value = false
  permTreeData.value = []
}



// 提交权限
const handlePermissionSubmit = async () => {
  try {
    submitting.value = true
    const ids = []

    // 收集选中的权限ID
    permTreeData.value.forEach(item => {
      if (item.children) {
        item.children.forEach(item2 => {
          if (item2.children && item2.children.length) {
            item2.children.forEach(item3 => {
              if (item3.ck) {
                ids.push(item3.id, item.id, item2.id)
              }
            })
          } else {
            if (item2.ck) {
              ids.push(item2.id, item.id)
            }
          }
        })
      }
    })

    // 去重
    const uniqueIds = [...new Set(ids)]

    // 调用API保存权限
    await roleApi.setRolePermissions(currentRole.value.id, uniqueIds)

    ElMessage.success(`权限分配成功！已为角色【${currentRole.value.role_name}】分配 ${selectedPermissionCount.value} 项权限`)
    permissionDialogVisible.value = false

  } catch (error) {
    console.error('保存权限失败:', error)
    ElMessage.error('保存权限失败')
  } finally {
    submitting.value = false
  }
}



// 生命周期
onMounted(() => {
  initData()
})
</script>

<style scoped>
.role-management {
  height: 100vh;
  background-color: #f5f7fa;
  overflow: hidden;
}

.role-container {
  height: 100%;
  background: white;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
}

/* 头部操作区 */
.header-actions {
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
}

/* 表格样式已移至公共样式文件 */



.edit-btn {
  color: #4a90e2;
}

.edit-btn:hover {
  background-color: #f0f9ff;
  color: #4a90e2;
}

.table-action-btn.delete-btn {
  color: #f56c6c;
}

.table-action-btn.delete-btn:hover {
  background-color: #fef0f0;
  color: #f56c6c;
}

.assign-btn {
  color: #409eff;
}

.assign-btn:hover {
  background-color: #f0f4ff;
  color: #409eff;
}

/* 权限分配对话框样式 */
.permission-dialog :deep(.el-dialog__header) {
  padding: 20px 24px 0;
  border-bottom: 1px solid #f0f0f0;
}

.permission-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.permission-dialog :deep(.el-dialog__footer) {
  padding: 16px 24px 24px;
  border-top: 1px solid #f0f0f0;
}



/* 权限内容区域 */
.permission-content {
  max-height: 70vh;
  overflow-y: auto;
  padding: 16px 24px;
}

/* 权限模块样式 */
.perm-module {
  margin-bottom: 20px;
  border: 1px solid #e8e9eb;
  border-radius: 8px;
  overflow: hidden;
  background: #ffffff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.module-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #f1f3f4 100%);
  border-bottom: 1px solid #e8e9eb;
}

.module-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.module-icon {
  color: #409eff;
  font-size: 18px;
}

.module-name {
  font-size: 16px;
  font-weight: 600;
  color: #1f2329;
}

.module-stats {
  font-size: 12px;
  color: #86909c;
  background: #f2f3f5;
  padding: 2px 8px;
  border-radius: 12px;
  margin-left: 8px;
}

.module-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.module-checkbox :deep(.el-checkbox__label) {
  font-weight: 500;
  color: #4e5969;
}



/* 模块内容 */
.module-content {
  padding: 16px 20px;
}

/* 权限分组样式 */
.perm-group {
  margin-bottom: 16px;
}

.group-with-children .group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #409eff;
}

.group-name {
  font-size: 14px;
  font-weight: 500;
  color: #4e5969;
}

.group-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}



/* 权限项样式 */
.group-permissions {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 8px 16px;
  padding-left: 16px;
}

.permission-item {
  margin: 0;
}

.permission-item :deep(.el-checkbox__label) {
  font-size: 13px;
  color: #646a73;
  line-height: 1.4;
}

.permission-item:hover :deep(.el-checkbox__label) {
  color: #409eff;
}

.permission-item.single {
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #52c41a;
}

.permission-item.single :deep(.el-checkbox__label) {
  font-weight: 500;
}

/* 动画效果 */
.perm-module {
  transition: all 0.3s ease;
}

.perm-module:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-1px);
}

.module-header {
  transition: background 0.3s ease;
}

.module-content {
  transition: all 0.3s ease;
}

.permission-item {
  transition: all 0.2s ease;
}

.permission-item:hover {
  background: rgba(64, 158, 255, 0.05);
  border-radius: 4px;
  padding: 2px 4px;
  margin: -2px -4px;
}

/* 复选框样式增强 */
.permission-item :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #409eff;
  border-color: #409eff;
}

.permission-item :deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
  background-color: #409eff;
  border-color: #409eff;
}

.module-checkbox :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #52c41a;
  border-color: #52c41a;
}

.module-checkbox :deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
  background-color: #faad14;
  border-color: #faad14;
}


/* 加载状态样式 */
.permission-content[v-loading] {
  min-height: 300px;
}

/* 空状态样式 */
.permission-empty {
  text-align: center;
  padding: 60px 20px;
  color: #86909c;
}

.permission-empty .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c9cdd4;
}

.permission-empty .empty-text {
  font-size: 16px;
  margin-bottom: 8px;
}

.permission-empty .empty-desc {
  font-size: 14px;
  color: #a9aeb8;
}



/* 对话框底部样式 */
.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.footer-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #86909c;
  font-size: 13px;
}

.footer-info .el-icon {
  color: #409eff;
}

.footer-actions {
  display: flex;
  gap: 12px;
}

.footer-actions .el-button {
  padding: 8px 24px;
  border-radius: 6px;
  font-weight: 500;
  min-width: 80px;
}

.footer-actions .el-button--default {
  background: #ffffff;
  border-color: #d9d9d9;
  color: #646a73;
}

.footer-actions .el-button--default:hover {
  background: #f5f7fa;
  border-color: #409eff;
  color: #409eff;
}

.footer-actions .el-button--primary {
  background: linear-gradient(135deg, #409eff 0%, #3a8ee6 100%);
  border-color: #409eff;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
}

.footer-actions .el-button--primary:hover {
  background: linear-gradient(135deg, #3a8ee6 0%, #337ecc 100%);
  border-color: #3a8ee6;
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.4);
}

/* 自定义滚动条 */
.role-table :deep(.el-table__body-wrapper)::-webkit-scrollbar,
.permission-tree::-webkit-scrollbar {
  width: 6px;
}

.role-table :deep(.el-table__body-wrapper)::-webkit-scrollbar-track,
.permission-tree::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.role-table :deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb,
.permission-tree::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.role-table :deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover,
.permission-tree::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.common-table-container {
  padding: 20px;
}
</style>
